const NewsService = require('../services/newsService');
const { formatResponse } = require('../utils/transform');

class NewsController {
  constructor() {
    this.newsService = new NewsService();
  }
  /**
   * 获取新闻列表（分页）
   * @param {Object} ctx - Koa上下文
   */
  async getNewsList(ctx) {
    try {
      const { current = 1, currentSize = 10 } = ctx.query;
      const page = parseInt(current, 10);
      const pageSize = parseInt(currentSize, 10);

      // 解析筛选条件
      const {
        keywords,
        classReal,
        addMode,
        timeRange,
        createTimeFrom,
        createTimeTo,
        isPublished,
        sortby
      } = ctx.query;

      // 将可能的数组或逗号分隔转换为数组
      const parseList = (v) => {
        if (!v) return undefined;
        if (Array.isArray(v)) return v.filter(Boolean);
        return String(v).split(',').map((x) => x.trim()).filter(Boolean);
      };

      const filters = {
        keywords: keywords ? String(keywords).trim() : undefined,
        classRealList: parseList(classReal)?.map((x) => parseInt(x, 10)).filter((n) => !Number.isNaN(n)) || (classReal ? [parseInt(classReal, 10)] : undefined),
        addMode: addMode !== undefined ? parseInt(addMode, 10) : undefined,
        // timeRange 可为数组或单独给出 from/to
        timeRange: (() => {
          if (Array.isArray(timeRange) && timeRange.length >= 2) return [timeRange[0], timeRange[1]];
          if (typeof timeRange === 'string') {
            const parts = timeRange.split(',').map((x) => x.trim());
            if (parts.length >= 2) return [parts[0], parts[1]];
          }
          if (createTimeFrom || createTimeTo) return [createTimeFrom, createTimeTo];
          return undefined;
        })(),
        isPublished: isPublished !== undefined ? parseInt(isPublished, 10) : undefined,
        // 将 sortby 解析为数字 0/1（0=降序，1=升序），否则忽略
        sortby: (() => {
          if (sortby === undefined) return undefined;
          const s = parseInt(sortby, 10);
          if (s === 0 || s === 1) return s;
          return undefined;
        })()
      };

      const data = await this.newsService.getNewsList(page, pageSize, filters);

      ctx.body = formatResponse(200, '获取成功', data);
    } catch (error) {
      ctx.body = formatResponse(500, '获取失败', error.message);
    }
  }

  /**
   * 创建新闻
   * @param {Object} ctx - Koa上下文
   */
  async createNews(ctx) {
    try {
      const body = ctx.request.body;
      const { newsTitle, title } = body;
      
      if (!newsTitle && !title) {
        ctx.body = formatResponse(400, '新闻标题不能为空', null);
        return;
      }
      
      // 从登录态记录操作人
      const operator = ctx.state?.user?.username || null;
      body.opPerson = operator;
      
      const newsId = await this.newsService.createNews(body);
      
      ctx.body = formatResponse(200, '添加成功', { id: newsId });
    } catch (error) {
      ctx.body = formatResponse(500, '添加失败', error.message);
    }
  }

  /**
   * 更新新闻
   * @param {Object} ctx - Koa上下文
   */
  async updateNews(ctx) {
    try {
      const body = ctx.request.body;
      const { id } = body;
      
      // 仅校验 id 必填，其他字段按需更新
      if (!id) {
        ctx.body = formatResponse(400, '新闻ID不能为空', null);
        return;
      }
      
      // 从登录态记录操作人
      const operator = ctx.state?.user?.username || null;
      body.opPerson = operator;
      
      const success = await this.newsService.updateNews(id, body);
      
      if (success) {
        ctx.body = formatResponse(200, '更新成功', null);
      } else {
        ctx.body = formatResponse(404, '新闻不存在', null);
      }
    } catch (error) {
      ctx.body = formatResponse(500, '更新失败', error.message);
    }
  }

  /**
   * 根据新闻ID获取新闻详情
   * @param {Object} ctx - Koa上下文
   */
  async getNewsById(ctx) {
    try {
      const id = Number(ctx.params?.id || ctx.query?.id || ctx.request.body?.id);
      if (!id) {
        ctx.body = formatResponse(400, '请提供有效的新闻ID', null);
        return;
      }
      const news = await this.newsService.getNewsById(id);
      if (!news) {
        ctx.body = formatResponse(404, '新闻不存在', null);
        return;
      }
      ctx.body = formatResponse(200, '获取成功', news);
    } catch (error) {
      ctx.body = formatResponse(500, '获取失败', error.message);
    }
  }

  /**
   * 获取各类别新闻数量
   * @param {Object} ctx - Koa上下文
   */
  async getNewsCountByClass(ctx) {
    try {
      const data = await this.newsService.getNewsCountByClass();
      
      ctx.body = formatResponse(200, '获取成功', data);
    } catch (error) {
      ctx.body = formatResponse(500, '获取失败', error.message);
    }
  }

  /**
   * 获取发布新闻详情
   * @param {Object} ctx - Koa上下文
   */
  async getPublishNewsById(ctx) {
    try {
      const body = ctx.request.body;
      const { id } = body;
      
      if (!id) {
        ctx.body = formatResponse(400, '新闻ID不能为空', null);
        return;
      }
      
      const publishNews = await this.newsService.getPublishNewsById(id);
      
      if (!publishNews) {
        ctx.body = formatResponse(404, '发布新闻不存在', null);
        return;
      }
      
      ctx.body = formatResponse(200, '获取成功', publishNews);
    } catch (error) {
      ctx.body = formatResponse(500, '获取失败', error.message);
    }
  }

  /**
   * 获取发布列表
   * @param {Object} ctx - Koa上下文
   */
  async getPublishList(ctx) {
    try {
      const body = ctx.request.body;
      const { current = 1, currentSize = 10, pubState } = body;
      const page = parseInt(current, 10);
      const pageSize = parseInt(currentSize, 10);
      
      const data = await this.newsService.getPublishList(page, pageSize, pubState);
      
      ctx.body = formatResponse(200, '获取成功', data);
    } catch (error) {
      ctx.body = formatResponse(500, '获取失败', error.message);
    }
  }

  /**
   * 立即发布
   * @param {Object} ctx - Koa上下文
   */
  async publishNewsNow(ctx) {
    try {
      const body = ctx.request.body;
      const { newsId, newsTitle } = body;
      
      if (!newsId || !newsTitle) {
        ctx.body = formatResponse(400, '新闻ID和标题不能为空', null);
        return;
      }
      
      const publishId = await this.newsService.publishNewsNow(body);
      
      ctx.body = formatResponse(200, '发布成功', { id: publishId });
    } catch (error) {
      ctx.body = formatResponse(500, '发布失败', error.message);
    }
  }

  /**
   * 定时发布
   * @param {Object} ctx - Koa上下文
   */
  async scheduleNewsPublish(ctx) {
    try {
      const body = ctx.request.body;
      const { newsId, newsTitle, waitPubTime } = body;
      
      if (!newsId || !newsTitle || !waitPubTime) {
        ctx.body = formatResponse(400, '新闻ID、标题和发布时间不能为空', null);
        return;
      }
      
      const publishId = await this.newsService.scheduleNewsPublish(body);
      
      ctx.body = formatResponse(200, '定时发布设置成功', { id: publishId });
    } catch (error) {
      ctx.body = formatResponse(500, '定时发布设置失败', error.message);
    }
  }

  /**
   * 更新发布定时
   * @param {Object} ctx - Koa上下文
   */
  async updatePublishSchedule(ctx) {
    try {
      const body = ctx.request.body;
      const { id, waitPubTime } = body;
      
      if (!id || !waitPubTime) {
        ctx.body = formatResponse(400, '发布ID和发布时间不能为空', null);
        return;
      }
      
      const success = await this.newsService.updatePublishSchedule(id, waitPubTime);
      
      if (success) {
        ctx.body = formatResponse(200, '更新成功', null);
      } else {
        ctx.body = formatResponse(404, '发布记录不存在', null);
      }
    } catch (error) {
      ctx.body = formatResponse(500, '更新失败', error.message);
    }
  }

  /**
   * 获取发布模板信息
   * @param {Object} ctx - Koa上下文
   */
  async getPublishTemplate(ctx) {
    try {
      const data = await this.newsService.getPublishTemplate();
      
      ctx.body = formatResponse(200, '获取成功', data);
    } catch (error) {
      ctx.body = formatResponse(500, '获取失败', error.message);
    }
  }

  /**
   * 获取选中列表
   * @param {Object} ctx - Koa上下文
   */
  async getSelectedNewsList(ctx) {
    try {
      const data = await this.newsService.getSelectedNewsList();
      
      ctx.body = formatResponse(200, '获取成功', data);
    } catch (error) {
      ctx.body = formatResponse(500, '获取失败', error.message);
    }
  }

  /**
   * 给选中列表排序
   * @param {Object} ctx - Koa上下文
   */
  async sortReleaseList(ctx) {
    try {
      const body = ctx.request.body;
      const { list } = body;
      // 确保list是数组
      const sortedList = Array.isArray(list) ? list : [];
      
      if (!sortedList || sortedList.length === 0) {
        ctx.body = formatResponse(400, '排序列表不能为空', null);
        return;
      }

      // 排序前校验：选中列表数量不能超过 10 条
      const selected = await this.newsService.getSelectedNewsList();
      if (selected.total > 10) {
        ctx.body = formatResponse(400, `选中列表数量不能超过10条，当前选中 ${selected.total} 条`, null);
        return;
      }
      
      const operator = ctx.state?.user?.username || null;
      await this.newsService.sortReleaseList(sortedList, operator);
      
      ctx.body = formatResponse(200, '排序成功', null);
    } catch (error) {
      ctx.body = formatResponse(500, '排序失败', error.message);
    }
  }

  /**
   * 删除新闻
   * @param {Object} ctx - Koa上下文
   */
  async deleteNews(ctx) {
    try {
      const body = ctx.request.body;
      const { ids } = body;
      
      if (!ids || !Array.isArray(ids) || ids.length === 0) {
        ctx.body = formatResponse(400, '请提供有效的新闻ID列表', null);
        return;
      }
      
      await this.newsService.deleteNews(ids);
      
      ctx.body = formatResponse(200, '删除成功', null);
    } catch (error) {
      ctx.body = formatResponse(500, '删除失败', error.message);
    }
  }

  async publishReleaseListAndClear(ctx) {
    try {
      const body = ctx.request.body || {};
      const waitPubTime = body.waitPubTime; // 可选定时发布时间

      // 发布期刊元数据（可选）
      const issueMeta = {
        title: body.issueTitle || body.title || null,
        coverImage: body.issueCoverImage || body.coverImage || null,
        description: body.issueDescription || body.description || null,
        publishTime: body.issuePublishTime || body.publishTime || null,
        publisher: body.issuePublisher || body.publisher || (ctx.state?.user?.username || null)
      };

      // 发布前校验：选中列表数量不能超过 10 条
      const selected = await this.newsService.getSelectedNewsList();
      if (selected.total > 10) {
        ctx.body = formatResponse(400, `每期刊发布的新闻数量不超过10，当前选中 ${selected.total} 条`, null);
        return;
      }

      const list = Array.isArray(body.list) ? body.list : [];
      const { publishedCount, issueNo, currentIssueNewsIds } = await this.newsService.publishReleaseListAndClear(list, waitPubTime, issueMeta);
      const msg = waitPubTime ? '定时发布已创建并清空选中列表' : '发布完成并清空选中列表';
      ctx.body = formatResponse(200, msg, { publishedCount, issueNo, currentIssueNewsIds });
    } catch (error) {
      ctx.body = formatResponse(500, '发布失败', error.message);
    }
  }

  /**
   * 获取issue期刊列表
   * @param {Object} ctx - Koa上下文
   */
  async getIssueList(ctx) {
    try {
      const body = ctx.request.body || {};
      const page = Number(body.current) || 1;
      const pageSize = Number(body.currentSize) || 10;
      const data = await this.newsService.getIssueList(page, pageSize);
      ctx.body = formatResponse(200, '获取成功', data);
    } catch (error) {
      ctx.body = formatResponse(500, '获取失败', error.message);
    }
  }
  /**
   * 根据issue期刊id获取对应的新闻列表（分页）
   * @param {Object} ctx - Koa上下文
   */
  async getIssueNews(ctx) {
    try {
      const query = ctx.query || ctx.request.query || {};
      const issueNo = Number(query.issueNo);
      if (!issueNo) {
        ctx.body = formatResponse(400, '请提供有效的期刊号 issueNo', null);
        return;
      }
      const data = await this.newsService.getIssueNews(issueNo);
      ctx.body = formatResponse(200, '获取成功', data);
    } catch (error) {
      ctx.body = formatResponse(500, '获取失败', error.message);
    }
  }
}

module.exports = NewsController;